<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class OfflineUser
 * @package App\Models
 * @version January 2, 2018, 8:38 am UTC
 *
 * @property string name
 * @property string true_name
 * @property  phone
 * @property string email
 * @property string roles
 * @property string avatar
 */
class OfflineUser extends Model
{
    use SoftDeletes;

    public $table = 'offline_users';


    protected $dates = ['deleted_at'];


    public $fillable = [
        'name',
        'true_name',
        'phone',
        'email',
        'roles',
        'avatar',
        'organization_id',
        'password',
        'status'
    ];

    public $hidden = [
        'password'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'name' => 'string',
        'true_name' => 'string',
        'email' => 'string',
        'avatar' => 'string',
        'organization_id' => 'integer'
    ];

    /**
     * 将资源转换成数组。
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray()
    {
        $mergeArray = [
            'organizations' => [],
        ];

        if (!is_null($this->organization)) {
            $mergeArray['organizations'] = Organization::ancestorsAndSelf($this->organization->id);
        }

        return array_merge(parent::toArray(), $mergeArray);
    }

    /**
     * 密码修改器。
     *
     * @param  string $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = md5($value);
    }

    public function getAvatarAttribute($value)
    {
        if (!$value) {
            return '';
        }

        return [
            'name' => $value,
            'url' => config('custom.file_visit_url') . '/' . $value
        ];
    }


    /**
     * 组织机构
     *
     * @return mixed
     */
    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }


}
